import json
import datetime
from django.db.models import Avg, Count, Min, Max, Sum

from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

# render请求
from green import models


def five(request):
    return render(request, "five/five.html")


def showFive(request):
    city = request.GET.get('cityName')
    print(city)
    f = open('templates/five/showFive.json', 'r', encoding='utf-8')
    bigJson = f.read()
    f.close()
    if city is None:
        data = json.loads(bigJson)['total']
    else:
        data = json.loads(bigJson)[city]
    data = {'data': data}
    response = HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
    return response


def initBigJsonForFive(request):
    # 参考Three
    bigJson = {}
    tempList = []
    yearList = [2016, 2017, 2018]
    for year in yearList:
        cars = {'year': year}
        queryData = models.Cityfactories.objects.all().aggregate(value=Sum('number_' + str(year) + 'factories'))

        cars['num'] = queryData['value']
        tempList.append(cars)
    bigJson['total'] = tempList
    print(bigJson)

    queryData = models.Cityfactories.objects.all().values()

    for cityData in queryData:
        tempList = []
        city = cityData['provence']
        for year in yearList:
            cars = {'year': year}
            cars['num'] = cityData['number_' + str(year) + 'factories']
            tempList.append(cars)
            # print(tempList)
        bigJson[city] = tempList
    print(bigJson)
    # 将bigJson保存为文件
    # bigJson = {}
    s = json.dumps(bigJson)
    f = open('../../templates/five/showFive.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print("构造bigJson.json成功！")
    return HttpResponse("构造成功！")


if __name__ == '__main__':
    initBigJsonForFive(0)
